package peer;

import java.awt.Rectangle;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.prefs.Preferences;

import javax.swing.filechooser.FileSystemView;

import peer.assist.AssistServer;
import peer.client.AssistClient;
import peer.client.ServerClient;
import peer.dstdb.DBServer;
import peer.httpoutput.HttpProcessorGroupMange;
import peer.httpoutput.HttpServer;
import peer.p2pnet.SourceNodeIdent;
import peer.p2pnet.SourceNodeMange;
import peer.p2pnet.message.AdvCSMessage1;
import peer.p2pnet.message.AdvCSMessage2;
import peer.p2pnet.message.CastGroupMessage;
import peer.p2pnet.message.CastGroupMessage2;
import peer.p2pnet.message.GetOutAddressMessage;
import peer.p2pnet.message.GetOutAddressMessage2;
import peer.p2pnet.message.GetSNodeMessage;
import peer.p2pnet.message.RegMessage;
import peer.p2pnet.message.RegMessage2;
import peer.rdp.ALManage;
import peer.rdp.AskFillMange;
import peer.rdp.ReSendMange;
import peer.rdp.Route;
import peer.rdpserver.SourceServer;
import peer.share.CacheFileMange;
import peer.share.PiecTempGroupMange;
import peer.share.RePubTimmer;
import peer.share.ShareFile;
import peer.share.ShareFileMange;
import peer.share.ShareFileStrMange;
import peer.share.SourceSessionIdMange;
import peer.tools.CharMap;
import peer.tools.FileTools;
import peer.tools.Mdb;
import peer.tools.MessageCheck;
import peer.tools.Setting;
import peer.tools.VTime;
import peer.webserver.AppletServer;

public class Config {
	static Ui ui;
	CharMap cm=new CharMap();
	public static HashSet<String> playerStr=new HashSet<String>();//常用播放器http请求特征字符串

	public static Setting shareFolderList;

	static int movieSum = 0;

	public static SourceNodeIdent lSni;

	public static short ver = 0;// 网络协议版本

	public static short nodeType_PubNet = 900;// 节点类型-公网

	public static short nodeType_LanNet = 901;// 节点类型-内网

	public static short myNodeType = nodeType_PubNet;// 本机节点类型
	
	//播放器广告
	public static String playerAdvUrlCSIni="http://61.155.169.23/ad2.html";
	public static String playerAdvUrlCS=playerAdvUrlCSIni;
	public static String advUrl="";
	
	//弹出广告
	static int advW=310;
	static int advH=210;
	static int advShowTime=10*1000;
	public static int advInterval=30*60*1000;

	// 基本文件目录
	public static String basePath = "./application/";

	public static String skinPath = basePath + "skin/";

	public static String mdfDir = basePath + "data/mdf/";// "C:/mdf/";

	public static String webDir = basePath + "web/";

	public static String jardllDir = basePath + "jardll/";

	public static File shareListFile;

	public static String cachePath =basePath + "data/cache.pp";// "C:/cache.pp";

	public static String tempPath =basePath+"data/temp.pi";// "C:/temp.pi";

	public static String mplayerPath = ".application/mplayer/MPlayer.exe";

	public static String htmlHelp = basePath + "帮助.html";

	public static String playerPath = "player.exe";

	// ui player
	public static boolean hideUi = true;// 隐藏ui界面

	public static boolean singleThread = true;// 运行单个ui实例

	public static boolean httpoutPort = true;// 当本地http端口被占用时，允许更换端口

	public static boolean singleAppletPort = false;// 单独AppletPort

	public static boolean checkNodeType = true;// 检测节点类型（公网或内网）

	public static boolean runPubNet = true;// 中心服务器运行于公网之上

	public static boolean uiVisual = true;// 允许查看Ui

	public static int uiPort = 41251;// Ui冲突端口

	public static int daePort = 45617;// player冲突端口

	public static String myAdvSize = "http://61.155.159.23/ad2.html";// 广告页面地址

	public static int appletPort = 63818;// applet网页播放器侦听端口

	// 缓存，共享
	public static SourceServer sourceServer;// 资源服务

	public static long delCacheSize = 1024 * 1024 * 1024 * 5;// 缓存文件最大体积1G 

	public static boolean cleanCache = false;// 退出删除缓存

	public static int CheckBlockInterval = 3 * 1000;// 检查完整分块延迟

	public static boolean savePmd2 = false;// 保存文件后缀名为“pmd2”

	public static ShareFileStrMange shareFileStrMange;// 共享文件路径名管理

	public static ShareFileMange shareFileMange;// 共享文件管理

	public static CacheFileMange cacheFileMange;// 缓存文件管理

	public static PiecTempGroupMange pieceTempGroupMange;// 临时分片管理

	public static SourceSessionIdMange sourceSessionIdMange;// 资源ID管理

	public static RePubTimmer rePubTimmer;// 发布计时器

	public static Thread rePubThread;// 重发布线程

	// Server 中心服务器客户端
	public static ServerClient serverClient;// 客户端

	static String cIpS = "61.155.169.23";// 中心服务器地址

	public static InetAddress cIp;// 中心服务器IP

	public static int cPort = 55551;// 中心服务器端口

	public static int sessionId = 0;// 中心服务器登录会话ID

	public static int groupEventOffset = 0;// 中心服务器事件序列

	public static boolean isLive = false;// 在线状态（中心服务器）

	public static int serverLiveTimeOut = 20000;// 超时时间

	public static int serverLiveInterval = 5000;// 发送心跳包间隔

	public static VTime vTime;// 虚拟时间

	// 搜索服务端
	public static DBServer dbServer;// 服务端

	public static int DBServerPort;// 搜索服务端口

	public static int sourceCleanTime = 1000 * 60 * 60;// 清理

	public static int loadDBTimeOut = 1000 * 60;// 装载索引数据超时时间

	public static int loadDBTimeOut_Tunnel = 1000 * 60 * 1;// //装载索引数据超时时间_Tunnel

	// 搜索客户端
	public static int synInterval = 5 * 1000;// 同步数据库节点表最小时间间隔

	public static int castIntervalMin = 10 * 1000;// 估算同步时间间隔

	public static int maxSearchNode = 1;// 每次发起搜索最多节点数

	// 协助服务端
	public static AssistServer assistServer;// 服务端

	public static int AssistServerPort;// 协助服务端口

	// 协助客户端
	public static AssistClient assistClient;// 客户端

	public static InetAddress assistNodeIp;// 协助节点地址

	public static int assistNodePort;// 协助节点端口

	public static boolean isReg = false;// 是否已注册协助节点

	public static int assistSessionId;// 协助服务会话ID

	public static boolean regSelfAssist = true;// 允许公网节点注册自己为协助节点

	public static int assistLiveTimeOut = 20 * 1000;// 协助节点超时

	public static int assistLiveInterval = 5 * 1000;// 向协助节点发送心跳包间隔

	// rudp 可靠udp
	public static InetAddress outIp;// 外网 IP

	public static int outPort;// 外网端口

	public static int RoutePort = 0;// rudp服务侦听端口

	public static Route route;// rudp 数据包路由管理

	public static ReSendMange reSendMange;// rudp重发管理

	public static AskFillMange askFillMange;// rudp确认管理

	public static int iniWin = 5;// 初始发送窗口

	public static int maxWin = 20;// 最大发送窗口

	public static int reFillTryTimes = 5;// 请求对方确认最大次数

	public static int reSendTryTimes = 5;// 请求对方重发最大次数

	public static int reFillMessageDelay2 = 1000;// 请求确认延迟2

	public static int reFillMessageDelay1 = 500;// 请求确认延迟1

	public static int reSendMessageDelay2 = 50;// 请求重发延迟2

	public static int reSendMessageDelay1 = 500;// 请求重发延迟1

	public static int alDetectinterval = 1;// 请求重发/确认扫描间隔

	public static int rdpActiveTimeOut = 30 * 1000;// rudp活动超时时间（长时间无实际数据传输）

	public static int sendLiveIntervalNomal = 5000;// rudp心跳包间隔（正常）

	public static int sendLiveIntervalBusy = 2000;// rudp心跳包间隔（繁忙）

	public static int liveTimeOut = 3 * sendLiveIntervalNomal;// rudp超时时间

	public static int receivePingTimeOut = 5000;// 接受ping超时时间

	public static int connectTimeOut = 5000;// 连接超时时间

	public static int pingTimeOut = 5000;// 接受ping超时时间

	public static ALManage delayAckManage;// rudp延迟确认管理

	public static boolean testSpeed = false;// 传输速度测试

	public static boolean testDrop = false;// 模拟丢包测试

	public static float drop = 0.1f;// 模拟丢包率

	public static ThreadPoolExecutor connectThreadPool;// rudp连接初始化线程池

	public static ThreadPoolExecutor tunnelCloseThreadPool;// 隧道关闭线程池

	public static ThreadPoolExecutor connectProcessorThreadPool;// rudp连接处理线程池

	public static ThreadPoolExecutor tunnelProcessorThreadPool;// rudp隧道处理线程池

	// 数据调度
	public static boolean httpFL = true;// 从共享文件输出

	public static int localHttpPort = 51687;// 本地http服务端口
	
	public static boolean verifyData_Down = false;// 输出下载时验证数据
	
	public static boolean verifyData_Play = false;// 输出播放时验证数据

	public static int maxPreLoadPiece = 50;// 最大预载分片数

	public static int maxLoadingPiece = 20;// 最大同时下载分片数

	public static int httpProcessorGroupCloseDelay = 10 * 1000;// HttpGroup延迟关闭时间

	public static int blockSearchinterval = 10 * 1000;// 分块搜索间隔

	public static int maxAvailSourceNode = 50;// 最大可用源节点数

	public static ThreadPoolExecutor transeThreadPool;// 分片传输线程池

	// SourceNode源节点
	public static SourceNodeMange sourceNodeMange;// 源节点管理

	public static int iniPieceWin = 1;// 初始分片窗口

	public static int maxPieceWin = 5;// 最大分片窗口

	public static int failWinReduce = 1;// 分片下载失败时减少窗口数

	public static int kickTime = 3 * 1000;// 

	public static int loadPieceTimeOut =5 * 1000;// 下载分片超时时间

	public static int resetPieceWinDelay = 6000 * 1000;// 重置分片窗口延迟(取消)

	public static int activeTimeOut = 60 * 1000;// 节点活跃超时时间

	public static int queryInterval = 5 * 1000;// 查询间隔

	public static int maxConnecFailTimes = 5;// 最大连接失败次数

	public static int reConnectDelay = 5 * 1000;// 重新连接延迟

	// 本地http服务器
	public static HttpServer httpServer;// 本地http服务器

	public static HttpProcessorGroupMange httpProcessorMange;// http处理进程管理

	public static AppletServer appletServer;// 提供网页applet播放器下载

	public static ThreadPoolExecutor httpThreadPool;// http线程池

	// 桌面文件夹同步
	static String synFolderUrl = "http://61.155.159.23/public/SynFolder.zip";// 同步文件url

	static String synFolderName = "MovieCache";// 同步文件夹名称

	public static int synFolderInterval = 30 * 60 * 1000;// 文件夹同步间隔

	public static FolderSynThread folderSynThread = null;// 桌面文件夹同步线程

	public static boolean useFolder = false;// 使用桌面文件夹

	// 广告
	public static String adv = "";// 当前广告页面地址

	static long lastSetAdvTime = 0;// 上次设置广告时间

	public static Thread resetPAdvThread;// 重置广告线程

	// 其他
	public static int checkLanIpServerPort = 95;// 检测内网地址时使用的端口

	public static InetAddress lanIp = null;// 内网IP

	public static Thread updateThread;// 软件升级线程

	public static HashMap ThreadStrTable = new HashMap();// 统计程序线程数

	/** 初始化本地环境 */
	static void iniLocal() {
		// 判断是否隐藏ui
		if (new File("nohide").exists()) {
			hideUi = false;
		}
		
		playerStr.add("User-Agent: MPlayer");
		playerStr.add("User-Agent: RMA");
		playerStr.add("User-Agent: Windows-Media-Player");
	//	playerStr.add("User-Agent: Mozilla");
		
		adv = getAdv2();
		autoInstall();
		ArrayBlockingQueue<Runnable> abq1 = new ArrayBlockingQueue<Runnable>(
				500);
		connectThreadPool = new ThreadPoolExecutor(10, 100, 5,
				TimeUnit.SECONDS, abq1);

		ArrayBlockingQueue<Runnable> abq2 = new ArrayBlockingQueue<Runnable>(
				500);
		connectProcessorThreadPool = new ThreadPoolExecutor(10, 100, 5,
				TimeUnit.SECONDS, abq2);

		ArrayBlockingQueue<Runnable> abq8 = new ArrayBlockingQueue<Runnable>(
				500);
		tunnelCloseThreadPool = new ThreadPoolExecutor(10, 100, 5,
				TimeUnit.SECONDS, abq8);

		ArrayBlockingQueue<Runnable> abq5 = new ArrayBlockingQueue<Runnable>(
				500);
		tunnelProcessorThreadPool = new ThreadPoolExecutor(10, 100, 5,
				TimeUnit.SECONDS, abq5);

		ArrayBlockingQueue<Runnable> abq3 = new ArrayBlockingQueue<Runnable>(
				500);
		transeThreadPool = new ThreadPoolExecutor(10, 100, 5, TimeUnit.SECONDS,
				abq3);

		ArrayBlockingQueue<Runnable> abq4 = new ArrayBlockingQueue<Runnable>(
				500);
		httpThreadPool = new ThreadPoolExecutor(10, 100, 5, TimeUnit.SECONDS,
				abq4);
		// 统计线程数
		new Thread() {
			public void run() {
				while (true) {
					System.out.println("ThreadPoolThreadPool "
							+ connectThreadPool.getActiveCount() + " "
							+ connectProcessorThreadPool.getActiveCount() + " "
							+ tunnelCloseThreadPool.getActiveCount() + " "
							+ tunnelProcessorThreadPool.getActiveCount() + " "
							+ transeThreadPool.getActiveCount() + " "
							+ httpThreadPool.getActiveCount());

					Iterator it = ThreadStrTable.keySet().iterator();
					while (it.hasNext()) {
						String str = (String) it.next();
						ThreadCounter tc = (ThreadCounter) ThreadStrTable
								.get(str);
						if (tc.conut > 0) {
							System.out.println("TSTR " + tc.conut + " " + str);
							if (str.equals("56jnjrtuy65")) {
								System.out.println("MAX56jnjrtuy65 " + tc.conut
										+ " " + tc.max);
							}
						}
					}

					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO 自动生成 catch 块
						e.printStackTrace();
					}
				}
			}
		};//.start();
		// 选择一个可用的route端口
		while (true) {
			RoutePort = peer.tools.RandomNum.randomInt(65505); 
			DatagramSocket ds = null;
			try {
				ds = new DatagramSocket(RoutePort);
			} catch (SocketException e) {
				e.printStackTrace();
				continue;
			} finally {
				ds.close();
			}
			break;
		}
		File baseDirFile = new File(basePath);
		File MdfDir = new File(basePath + "\\mdf\\");
		shareListFile = new File(basePath + "\\sfl.cfg");
		if (!baseDirFile.exists()) {
			baseDirFile.mkdirs();
		}
		if (!MdfDir.exists()) {
			MdfDir.mkdir();
		}

		// 启动各种服务
		appletServer = new AppletServer();

		sourceSessionIdMange = new SourceSessionIdMange();

		shareFileMange = new ShareFileMange();
		shareFileStrMange = new ShareFileStrMange();
		cacheFileMange = new CacheFileMange();
		pieceTempGroupMange = new PiecTempGroupMange();

		delayAckManage = new ALManage();
		reSendMange = new ReSendMange();
		askFillMange = new AskFillMange();

		dbServer = new DBServer();
		assistServer = new AssistServer();

		httpServer = new HttpServer();
		httpProcessorMange = new HttpProcessorGroupMange();

		rePubTimmer = new RePubTimmer();
		
		AdvWin.ini();
		
		resetPAdvThread = new Thread() {
			public void run() {
				while (true) {
					if (System.currentTimeMillis() - lastSetAdvTime > 5 * 1000) {
						setPAdv(myAdvSize);
					}
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}
		};
		resetPAdvThread.start();
		rePubThread = new Thread() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(20 * 60 * 1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					shareFileMange.pubAllFile();
					cacheFileMange.pubAllCache();
				}
			}
		};
		rePubThread.start();
		updateThread = new Thread() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(60 * 60 * 1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					runUpdate();
				}
			}
		};
		updateThread.start();
	}

	/** 运行升级程序-静默更新 */
	public static void runUpdate() {
		File file = new File("updater.exe");
		if (file.exists()) {
			try {
				Runtime.getRuntime().exec(
						file.getAbsolutePath() + " /silentall");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/** 运行升级程序-立即更新 */
	public static void runUpdate2() {
		File file = new File("updater.exe");
		if (file.exists()) {
			try {
				Runtime.getRuntime()
						.exec(file.getAbsolutePath() + " /checknow");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/** 初始化网络环境，登陆并发布共享 */
	static void iniNet() {
		folderSynThread = new FolderSynThread();
		while (true) {
			try {
				cIp = InetAddress.getByName(cIpS);
				break;
			} catch (UnknownHostException e) {
				e.printStackTrace();
				try {
					Thread.sleep(10 * 1000);
				} catch (InterruptedException e2) {
					e2.printStackTrace();
				}
			}

		}
		getAdvFromCS();
		vTime = new VTime(cIp, cPort);
		getLanIp();
		getOutAddress();
		try {
			route = new Route(Config.RoutePort);
			sourceNodeMange = new SourceNodeMange();
			sourceServer = new SourceServer();
			loginServer();
			regAssistNode();
			shareFileMange.pubAllFile();
			cacheFileMange.pubAllCache();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/** 获取本机局域网IP */
	static void getLanIp() {
		while (true) {
			try {
				Socket ss = new Socket(cIp, checkLanIpServerPort);
				lanIp = ss.getLocalAddress();
				ss.close();
				return;
			} catch (IOException e) {
				// e.printStackTrace();
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				continue;
			}
		}

	}

	public static void println(String str) {
		System.out.println(str);
	}

	public static void printlnCS(String str) {
		System.out.println("     " + "toCServer " + str);
	}

	public static void printlnASS(String str) {
		System.out.println("          " + "toAssist " + str);
	}

	public static void printlnDB(String str) {
		System.out.println("               " + "toDBNode " + str);
	}

	public static void printlnASS2(String str) {
		System.out
				.println("                                                                  "
						+ "Assist "
						+ str
						+ " "
						+ System.currentTimeMillis()
						/ 1000);
	}

	public static void printlnDB2(String str) {
		System.out
				.println("                                                                                  "
						+ "DBNode " + str);
	}

	void copyFile(File file, File f1) throws IOException {
		FileOutputStream fos = null;
		FileInputStream fis = null;
		try {
			f1.createNewFile();
			fos = new FileOutputStream(f1);
			fis = new FileInputStream(file);
			byte[] buffer = new byte[1024 * 100];
			int length = 0;
			while ((length = fis.read(buffer)) != -1) {
				fos.write(buffer, 0, length);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/** 添加注册表内容 */
	static void addRegContent(String key, String value) {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		userPrefs.put(key, value);
	}

	/** 获取注册表内容 */
	static String getRegContent(String key) {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		return userPrefs.get(key, "");
	}

	/** 生成注册表文件，向浏览器注册lightvod协议 */
	public static void addAutoReg() {
//		String s = new File(".").getAbsolutePath();
//		String currentPaht = s.substring(0, s.length() - 1);
//		StringBuffer sb = new StringBuffer();
//		StringTokenizer st = new StringTokenizer(currentPaht, "\\");
//		while (st.hasMoreTokens()) {
//			sb.append(st.nextToken());
//			sb.append("\\\\");
//		}
//		ArrayList<String> list = new ArrayList<String>();
//		list.add("Windows Registry Editor Version 5.00");
//		// list.add("[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run]");
//		// list.add("\"LightP2P\"=\""+sb.toString()+"ui.exe min"+"\"");
//
//		list.add("[HKEY_CLASSES_ROOT\\lightvod]");
//		list.add("@=\"lightvod Protocol\"");
//		list.add("\"URL Protocol\"=\"\"");
//		list.add("[HKEY_CLASSES_ROOT\\lightvod\\shell]");
//		list.add("@=\"open\" ");
//		list.add("[HKEY_CLASSES_ROOT\\lightvod\\shell\\open] ");
//		list.add("[HKEY_CLASSES_ROOT\\lightvod\\shell\\open\\command]");
//		String sss = "@=\"\\\"" + sb.toString() + "player.exe\\\" \\\"%1\\\"\"";
//		list.add(sss);
//		list.add("");
//		File file = null;
//		try {
//			file = new File("import.reg");
//			FileWriter fw = new FileWriter(file);
//			PrintWriter pw = new PrintWriter(fw);
//			for (int i = 0; i < list.size(); i++) {
//				String ss = list.get(i);
//				if (!ss.equals("")) {
//					pw.println(ss);
//				}
//			}
//			pw.flush();
//			pw.close();
//			Process p = Runtime.getRuntime().exec("regedit /s " + "import.reg");
//			p.waitFor();
//		} catch (FileNotFoundException e1) {
//			e1.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		} finally {
//			if (file != null) {
//				file.delete();
//			}
//		}
	}

	/** 设置是否启用桌面文件夹 */
	public static void setUseFolder(boolean use) {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		userPrefs.putBoolean("usefolder", use);
	}

	/** 检查是否启用桌面文件夹 */
	public static boolean getUseFolder() {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		return userPrefs.getBoolean("usefolder", true);
	}

	/** 设置自动运行 */
	public static void setAutoRun(boolean run) {
//		String s = new File(".").getAbsolutePath();
//		String currentPaht = s.substring(0, s.length() - 1);
//		StringBuffer sb = new StringBuffer();
//		StringTokenizer st = new StringTokenizer(currentPaht, "\\");
//		while (st.hasMoreTokens()) {
//			sb.append(st.nextToken());
//			sb.append("\\\\");
//		}
//		ArrayList<String> list = new ArrayList<String>();
//		list.add("Windows Registry Editor Version 5.00");
//		list
//				.add("[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run]");
//		if (run) {
//			list.add("\"LightP2P\"=\"" + sb.toString() + "ui.exe -min" + "\"");
//		} else {
//			list.add("\"LightP2P\"=\"" + "null\"");
//		}
//
//		File file = null;
//		try {
//			file = new File("import.reg");
//			FileWriter fw = new FileWriter(file);
//			PrintWriter pw = new PrintWriter(fw);
//			for (int i = 0; i < list.size(); i++) {
//				String ss = list.get(i);
//				if (!ss.equals("")) {
//					pw.println(ss);
//				}
//			}
//			pw.flush();
//			pw.close();
//			Process p = Runtime.getRuntime().exec("regedit /s " + "import.reg");
//			p.waitFor();
//		} catch (Exception e1) {
//			// e1.printStackTrace();
//		} finally {
//			if (file != null) {
//				file.delete();
//			}
//		}
//
//		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
//		userPrefs.putBoolean("autoRun", run);
	}

	/** 检查自动运行 */
	public static boolean getAutoRun() {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		return userPrefs.getBoolean("autoRun", true);
	}

	/** 关联协议，拷贝一些dll文件 */
	static void autoInstall() {
		addAutoReg();
		File f = new File(mplayerPath);
		addRegContent("mplayerpath", f.getAbsolutePath());
		// dll
		// String javaHome=System.getProperty("java.home");
		// String dll1="swt-awt-win32-3236.dll";
		// String dll2="swt-win32-3236.dll";
		// String dllPath=javaHome+"\\bin";
		// checkFile(dllPath,dll1);
		// checkFile(dllPath,dll2);
		/*
		 * //jar String jar0="peer.jar"; String jar1="forms-1.0.6.jar"; String
		 * jar2="miglayout-swing.jar"; String jar3="swing2swt.jar"; String
		 * jar4="swt.jar"; String jar5="tools.jar"; String
		 * jarPath=javaHome+"\\lib\\applet"; checkFile(jarPath,jar0);
		 * checkFile(jarPath,jar1); checkFile(jarPath,jar2);
		 * checkFile(jarPath,jar3); checkFile(jarPath,jar4);
		 * checkFile(jarPath,jar5); //appletWebJar String peerJar="peer.jar";
		 * checkFile(webDir,peerJar);
		 */
	}

	void checkFile(String path, String fs) {
		File f1 = new File(path + "/" + fs);
		File file = new File(jardllDir + fs);
		if (file.exists()) {
			if (!f1.exists() | f1.lastModified() < file.lastModified()) {
				System.out.println("ddddwww " + file + "###" + f1);
				try {
					copyFile(file, f1);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	/** 获取外部地址 */
	static void getOutAddress() {
		Config.printlnCS("获取外部地址...  " + cPort + " RoutePort " + RoutePort);
		DatagramSocket ds = null;
		try {
			ds = new DatagramSocket(Config.RoutePort);
			ds.setSoTimeout(3000);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		GetOutAddressMessage goam = new GetOutAddressMessage();
		goam.setDstAddress(cIp);
		goam.setDstPort(cPort);

		byte[] data = new byte[1024];
		DatagramPacket dp2 = new DatagramPacket(data, data.length);
		while (true) {
			try {
				ds.send(goam.getDatagramPacket());
				ds.receive(dp2);
			} catch (IOException e) {
				System.out.println("获取外部地址超时");
				continue;
			}
			if (MessageCheck.checkSType(dp2) == peer.tools.MessageType.sType_getOutAddressMessage2) {
				ds.close();
				GetOutAddressMessage2 goam2 = new GetOutAddressMessage2(dp2);
				Config.outIp = goam2.getOutIp();
				Config.outPort = goam2.getOutPort();
				Enumeration enums = null;
				HashMap<InetAddress, ?> hm = new HashMap();
				try {
					enums = NetworkInterface.getNetworkInterfaces();
					while (enums.hasMoreElements()) {
						NetworkInterface ni = (NetworkInterface) enums
								.nextElement();
						Enumeration ips = ni.getInetAddresses();
						while (ips.hasMoreElements()) {
							InetAddress ip = (InetAddress) ips.nextElement();
							hm.put(ip, null);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
				if (checkNodeType) {
					boolean isPubIp = false;
					if (runPubNet) {
						isPubIp = peer.tools.IpChecker.isPubIp(Config.outIp);
					} else {
						isPubIp = true;
					}
					if (Config.RoutePort == Config.outPort
							& hm.containsKey(Config.outIp) & isPubIp) {
						Config.myNodeType = Config.nodeType_PubNet;
					} else {
						Config.myNodeType = Config.nodeType_LanNet;
					}
				}
				Config.printlnCS("外部地址 " + Config.outIp + ":" + Config.outPort
						+ "  " + Config.myNodeType);
				return;
			}
		}
	}

	/** 登录服务器 */
	static void loginServer() throws SocketException {
		DatagramSocket ds = null;
		Config.printlnCS("登录...");
		try {
			ds = new DatagramSocket();
			ds.setSoTimeout(3000);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		RegMessage rm = new RegMessage();
		rm.setDstAddress(Config.cIp);
		rm.setDstPort(Config.cPort);
		int tryTimes = 0;
		while (!isLive) {
			tryTimes++;
			Config.printlnCS("尝试第" + tryTimes + "次登录");
			try {
				ds.send(rm.getDatagramPacket());
			} catch (IOException e) {
				e.printStackTrace();
			}
			byte[] data = new byte[1024];
			DatagramPacket dp = new DatagramPacket(data, data.length);
			try {
				ds.receive(dp);
			} catch (IOException e) {
				Config.printlnCS("登录超时");
				continue;
			}
			if (peer.tools.MessageCheck.checkVer(dp) == Config.ver) {
				if (peer.tools.MessageCheck.checkSType(dp) == peer.tools.MessageType.sType_RegMessage2) {
					RegMessage2 rm2 = new RegMessage2(dp);
					int sessionId = rm2.getSessionId();
					Config.sessionId = sessionId;
					ds.close();
					peer.Config.isLive = true;
					try {
						// 登录成功，启动客户端并同步虚拟时间
						Config.serverClient = new ServerClient();
						Config.printlnCS("登录成功" + " ServerSession:"
								+ Config.sessionId);
						vTime.synNow();
						break;
					} catch (SocketException e) {
						e.printStackTrace();
						throw e;
					}

				}
			}
		}
	}

	/** 服务器下线后的处理方法 */
	public static void serverOffline() {
		Config.printlnCS("服务器下线 重新登录");
		peer.Config.isLive = false;
		// 停止所有发布线程
		HashMap<Mdb, ShareFile> mdFileTable = Config.shareFileMange
				.getMDFileTable();
		Iterator<Mdb> it = mdFileTable.keySet().iterator();
		while (it.hasNext()) {
			Mdb mdb = it.next();
			ShareFile fi = mdFileTable.get(mdb);
			fi.isPub = false;
			fi.stopAllThread();
			fi.stopAllThread();
		}
		// 改变所有资源ID
		peer.Config.sourceSessionIdMange.changeAllSessionId();
		// 搜索服务重置所有索引数据
		peer.Config.dbServer.resetDataBase();
		// 重新登录服务器
		try {
			loginServer();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		// 发布资源
		shareFileMange.pubAllFile();
		cacheFileMange.pubAllCache();
		rePubTimmer.reStart();
	}

	/** 注册（登录）协助节点 */
	public static void regAssistNode() {
		Config.printlnASS("注册协助节点");
		int tryTimes = 0;
		while (true) {
			if (Config.myNodeType == Config.nodeType_PubNet & regSelfAssist) {
				Config.printlnASS("注册本机为协助节点");
				Config.assistNodeIp = Config.outIp;
				Config.assistNodePort = Config.AssistServerPort;
			} else {

				// 向服务器查询协助节点地址
				byte[] b = new byte[100];
				DatagramPacket dp = new DatagramPacket(b, b.length);
				DatagramSocket ds = null;
				try {
					ds = new DatagramSocket();
					ds.setSoTimeout(3000);
				} catch (SocketException e) {
					e.printStackTrace();
				}
				GetSNodeMessage gsm = new GetSNodeMessage();
				gsm.setDstAddress(Config.cIp);
				gsm.setDstPort(Config.cPort);
				while (true) {
					tryTimes++;
					Config.printlnASS("尝试第" + tryTimes + "次获取协助节点地址");
					try {
						ds.send(gsm.getDatagramPacket());
					} catch (IOException e) {
						e.printStackTrace();
					}
					try {
						ds.receive(dp);
					} catch (IOException e) {
						Config.printlnASS("获取协助结点地址超时");
					}

					if (MessageCheck.checkSType(dp) == peer.tools.MessageType.sType_GetSNodeMessage2) {
						GetOutAddressMessage2 goam2 = new GetOutAddressMessage2(
								dp);
						InetAddress in = null;
						try {
							in = InetAddress.getByName("0.0.0.0");
						} catch (UnknownHostException e) {
							e.printStackTrace();
						}
						if (goam2.getOutIp().equals(in)) {
							try {
								Thread.sleep(3000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							continue;
						}
						Config.assistNodeIp = goam2.getOutIp();
						Config.assistNodePort = goam2.getOutPort();
						Config.printlnASS("成功获取协助节点地址 " + Config.assistNodeIp
								+ ":" + Config.assistNodePort);
						break;
					}
				}
			}

			// 注册查询到的协助结点
			byte[] b = new byte[100];
			DatagramPacket dp = new DatagramPacket(b, b.length);
			DatagramSocket ds2 = null;
			try {
				ds2 = new DatagramSocket();
			} catch (SocketException e) {
				e.printStackTrace();
			}
			try {
				ds2.setSoTimeout(3000);
			} catch (SocketException e1) {
				e1.printStackTrace();
			}
			peer.assist.message.RegMessage rm = new peer.assist.message.RegMessage(
					Config.outIp, Config.outPort, lanIp, RoutePort);
			rm.setDstAddress(Config.assistNodeIp);
			rm.setDstPort(Config.assistNodePort);
			int tryTimes2 = 0;
			while (tryTimes2 < 3) {
				tryTimes2++;
				Config.printlnASS("尝试第" + tryTimes2 + "次注册");
				try {
					ds2.send(rm.getDatagramPacket());
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					ds2.receive(dp);
				} catch (IOException e) {
					Config.printlnASS("注册协助结点超时");
					if (tryTimes2 == 3) {
						Config.printlnASS("注册协助结点失败");
						break;
					} else {
						continue;
					}
				}
				if (MessageCheck.checkSType(dp) == peer.tools.MessageType.sType_Assist_RegMessage2) {
					peer.assist.message.RegMessage2 rm2 = new peer.assist.message.RegMessage2(
							dp);
					Config.assistSessionId = rm2.getSessionId();
					Config.lSni = new SourceNodeIdent(Config.assistSessionId,
							Config.assistNodeIp, Config.assistNodePort);
					ds2.close();
					Config.printlnASS("成功注册协助结点" + Config.assistNodeIp + ":"
							+ Config.assistNodePort + " "
							+ Config.assistSessionId);
					isReg = true;
					// 运行协助客户端
					assistClient = new AssistClient();
					return;
				} else {
					continue;
				}
			}
		}
	}

	/** 协助节点下线处理方法 */
	public static void assistNodeOffline() {
		// 重新注册一个协助节点
		regAssistNode();
		// 重新发布共享文件信息
		shareFileMange.pubAllFile_ReRegAssist();
		// 重新发布缓存信息
		cacheFileMange.pubAllCache_ReRegAssist();
		rePubTimmer.reStart();
	}

	/** 获取某资源对应的搜索节点组列表 */
	public static HashMap loadDBNodeList(Mdb mdb, boolean c) {
		HashMap nodeList = null;
		CastGroupMessage cgm = new CastGroupMessage(mdb.md);
		cgm.setDstAddress(Config.cIp);
		cgm.setDstPort(Config.cPort);
		DatagramSocket ds = null;
		try {
			ds = new DatagramSocket();
			ds.setSoTimeout(5000);
			int tryTimes = 0;
			while (tryTimes < 5) {
				tryTimes++;
				try {
					ds.send(cgm.getDatagramPacket());
					byte[] data = new byte[1000];
					DatagramPacket dp = new DatagramPacket(data, data.length);
					ds.receive(dp);
					if (MessageCheck.checkSType(dp) == peer.tools.MessageType.sType_CastGroupMessage2) {
						CastGroupMessage2 cgm2 = new CastGroupMessage2(dp, mdb);
						nodeList = cgm2.getCastMemberTable();
						if (nodeList.size() != 0) {
							break;
						} else {
							if (c) {
								try {
									Thread.sleep(5000);
								} catch (InterruptedException e) {
									// e.printStackTrace();
								}
								continue;
							} else {
								break;
							}
						}
					}
				} catch (IOException e1) {
					continue;
				}
			}
		} catch (SocketException e1) {
			e1.printStackTrace();
		} finally {
			if (ds != null) {
				ds.close();
			}
		}
		return nodeList;
	}

	/** 打开浏览器 */
	public static void openUrl(String address) {
		try {
			Runtime.getRuntime().exec("cmd /c start   " + address);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** 用播放器播放资源 */
	public static void playUrl(String address) {
		File file = new File("player.exe");
		if (file.exists()) {
			try {
				Runtime.getRuntime().exec(
						file.getAbsolutePath() + " " + address);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void setLastOpenDirConsole(String path) {
		addRegContent("opendirc", path);
	}

	public static String getLastOpenDirConsole() {
		return getRegContent("opendirc");
	}

	public static long getLastFolderSynTime() {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		return userPrefs.getLong("folderSyn", 0);
	}

	public static void setLastFolderSynTime(long time) {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		userPrefs.putLong("folderSyn", time);
	}

	public static void setMainFrameBound(Rectangle rec) {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p/cb");
		userPrefs.putInt("x", rec.x);
		userPrefs.putInt("y", rec.y);
		userPrefs.putInt("width", rec.width);
		userPrefs.putInt("height", rec.height);
	}

	public static Rectangle getMainFrameBound() {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p/cb");
		int x = userPrefs.getInt("x", 400);
		int y = userPrefs.getInt("y", 300);
		int width = userPrefs.getInt("width", 600);
		int height = userPrefs.getInt("height", 500);

		return new Rectangle(x, y, width, height);
	}

	public static void setVolume(int vol) {
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		userPrefs.putInt("volume", vol);
	}

	public static int getVolume() {
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		return userPrefs.getInt("volume", 100);
	}

	public static void setPlayerOSD(int level) {
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		userPrefs.putInt("osdlever", level);
	}

	public static int getPlayerOSD() {
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		return userPrefs.getInt("osdlever", 0);
	}

	public static org.eclipse.swt.graphics.Rectangle getPBound() {
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		int x = userPrefs.getInt("x", 400);
		int y = userPrefs.getInt("y", 100);
		int width = userPrefs.getInt("width", 600);
		int height = userPrefs.getInt("height", 500);
		return new org.eclipse.swt.graphics.Rectangle(x, y, width, height);
	}

	public static void setPBound(org.eclipse.swt.graphics.Rectangle rec) {
		if (rec.y < 0) {
			rec.y = 0;
		}
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		userPrefs.putInt("x", rec.x);
		userPrefs.putInt("y", rec.y);
		userPrefs.putInt("width", rec.width);
		userPrefs.putInt("height", rec.height);
	}

	public static long getVTime() {
		if (vTime != null) {
			// System.out.println("KKKKKKKKK "+new
			// Date(vTime.getCurrentTime()));
			return vTime.getCurrentTime();
		} else {
			return System.currentTimeMillis();
		}
	}

	public static void setAdv2(String adv2) {
		adv = adv2;
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		userPrefs.put("adv", adv2);
	}

	public static String getAdv2() {
		Preferences userPrefs = Preferences.userRoot().node("lightp2p");
		return userPrefs.get("adv", "");
	}

	public static String getAdv() {
		return adv;
	}

	public static void resetPAdv() {
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		userPrefs.put("padv", myAdvSize);
	}

	public static void setPAdv(String adv) {
		if (System.currentTimeMillis() - lastSetAdvTime > 2000) {
			lastSetAdvTime = System.currentTimeMillis();
			Preferences userPrefs = Preferences.userRoot().node("lightplayer");
			userPrefs.put("padv", adv);
		}
	}

	public static String getPAdv() {
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		return userPrefs.get("padv", myAdvSize);
	}

	/** 关联默认格式 */
	public static void assFile() {
		new Thread() {
			public void run() {
				assFormat("wmv");
				assFormat("rm");
				assFormat("rmvb");
				assFormat("avi");
				assFormat("mpg");
				assFormat("mpeg");
				assFormat("lv");
			}
		}.start();
	}

	/** 关联格式 */
	public static void assFormat(String format) {
//		String s = new File(".").getAbsolutePath();
//		String currentPaht = s.substring(0, s.length() - 1);
//		StringBuffer sb = new StringBuffer();
//		StringTokenizer st = new StringTokenizer(currentPaht, "\\");
//		while (st.hasMoreTokens()) {
//			sb.append(st.nextToken());
//			sb.append("\\\\");
//		}
//		ArrayList<String> list = new ArrayList<String>();
//		list.add("Windows Registry Editor Version 5.00");
//		list.add("[HKEY_CLASSES_ROOT\\." + format + "]");
//		list.add("@=\"" + format + ".file\"");
//		list.add("[HKEY_CLASSES_ROOT\\" + format
//				+ ".file\\shell\\open\\command]");
//		String sss = "@=\"\\\"" + sb.toString() + "player.exe\\\" \\\"%1\\\"\"";
//		list.add(sss);
//
//		list.add("[HKEY_CLASSES_ROOT\\" + format + ".file\\DefaultIcon]");
//		String sss2 = "@=\"" + sb.toString() + "application\\\\real.ico" + "\"";
//		list.add(sss2);
//		File file = null;
//		try {
//			file = new File("import.reg");
//			FileWriter fw = new FileWriter(file);
//			PrintWriter pw = new PrintWriter(fw);
//			for (int i = 0; i < list.size(); i++) {
//				String ss = list.get(i);
//				if (!ss.equals("")) {
//					pw.println(ss);
//				}
//			}
//			pw.flush();
//			pw.close();
//			Process p = Runtime.getRuntime().exec("regedit /s " + "import.reg");
//			p.waitFor();
//		} catch (FileNotFoundException e1) {
//			e1.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		} finally {
//			if (file != null) {
//				file.delete();
//			}
//		}
	}

	/** 同步桌面文件夹 */
	public static void synMovieFolder() {
		new Thread() {
			public void run() {
				for (int i = 0; i < 5; i++) {
					try {
						String zipFile = File.createTempFile("synfolder" + i,
								"zip").getAbsolutePath();
						FileTools.downloadFile(synFolderUrl, zipFile);
						String path = getSynPath();
						FileTools.deleteDir(path);
						try {
							FileTools.unZip(zipFile, path);
						} catch (Exception e) {
							e.printStackTrace();
						}
						break;
					} catch (IOException e1) {
						e1.printStackTrace();
						try {
							Thread.sleep(5000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}.start();
	}
	
	public static String gePlayerAdvUrlCS(){
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		return userPrefs.get("playeradvurlcs", playerAdvUrlCSIni);
	}
	
	public static void setPlayerAdvUrlCS(String url){
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		userPrefs.put("playeradvurlcs", url);
	}

	public static float getPlayerAdvRateCS(){
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		return userPrefs.getFloat("playeradvratecs", 0);
	}
	
	public static void setPlayerAdvRateCS(float rate){
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		userPrefs.putFloat("playeradvratecs", rate);
	}
	
	public static void getAdvFromCS() {
		new Thread() {
			public void run() {
				DatagramSocket ds=null;
				try {
					cIp=InetAddress.getByName(cIpS);
					ds = new DatagramSocket();
					ds.setSoTimeout(3000);
				} catch (SocketException e) {
					e.printStackTrace();
					return;
				} catch (UnknownHostException e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}
				for (int i = 0; i < 10; i++) {
					
					AdvCSMessage1 acm1=new AdvCSMessage1();
					acm1.setDstAddress(cIp);
					acm1.setDstPort(cPort);
					try {
						ds.send(acm1.getDatagramPacket());
					} catch (IOException e) {
						e.printStackTrace();
						return;
					}
					
					byte[] data=new byte[1000];
					DatagramPacket dp=new DatagramPacket(data, data.length);
					try {
						ds.receive(dp);
					} catch (IOException e) {
						//e.printStackTrace();
						continue;
					}
					int sType=peer.tools.MessageCheck.checkSType(dp);
					if(sType==peer.tools.MessageType.sType_AdvCSMessage2){
						AdvCSMessage2 acm2=new AdvCSMessage2(dp);
						setPlayerAdvUrlCS(acm2.getAdvUrl());
						setPlayerAdvRateCS(acm2.getAdvRate());
						System.out.println("QQQQQQ "+acm2.getAdvRate()+" "+acm2.getAdvUrl());
						System.out.println("PPPPPP "+getPlayerAdvRateCS()+" "+gePlayerAdvUrlCS());
						break;
						
					}
				}
			}
		}.start();
	}

	public static String getSynPath() {
		String path = "C:" + File.separator + synFolderName;
		return path;
	}

	public static void updateSynFolderLink() {
//		movieSum = 0;
//		calMovieSum(new File(getSynPath()));
//		FileSystemView fsv = FileSystemView.getFileSystemView();
//		File[] files = fsv.getHomeDirectory().listFiles();
//		for (int i = 0; i < files.length; i++) {
//			File file = files[i];
//			String path = file.getAbsolutePath();
//			String name = file.getName();
//			if (name.startsWith("电影^") & path.endsWith(".lnk")) {
//				file.delete();
//			}
//		}
//		if (getUseFolder()) {
//			if (movieSum > 0) {
//				String path = fsv.getHomeDirectory().getAbsolutePath()
//						+ File.separator + "电影^" + movieSum + "部" + ".lnk";
//				String path2 = "\"" + path + "\"";
//				String command = "XXMKLINK.exe " + path2 + " \"" + getSynPath()
//						+ "\"";
//				try {
//					Runtime.getRuntime().exec(command);
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//
//		}

	}
	
	public static String getPlayerAdvUrl(){
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		return userPrefs.get("playerAdvUrl", playerAdvUrlCS);
	}
	
	public static void setPlayerAdvUrl(String url){
		Preferences userPrefs = Preferences.userRoot().node("lightplayer");
		userPrefs.put("playerAdvUrl", url);
	}

	static void calMovieSum(File file) {
		String name = file.getName();
		HashSet<String> set = new HashSet<String>();
		set.add("0");
		set.add("2");
		set.add("3");
		set.add("4");
		set.add("5");
		set.add("6");
		set.add("7");
		set.add("8");
		set.add("9");
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				calMovieSum(files[i]);
			}
		} else {
			if (name.endsWith(".lv")) {
				if (name.endsWith("1.lv")) {
					movieSum++;
					// System.out.println("asas"+file.getAbsolutePath());
				} else {
					if (name.length() >= 4) {
						String ls = name.substring(name.length() - 4, name
								.length());
						String s = ls.substring(0, 1);
						if (!set.contains(s)) {
							movieSum++;
							// System.out.println("qqqq"+file.getAbsolutePath());
						}

					}
				}
			}
		}
	}

}
